package com.gksc.video.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @className: TaskPoolConfig
 * @description: 线程池配置
 * @author: Liao.yx
 * @email: 1229053515@qq.com
 * @create: 2021年05月14日 16时33分
 * @copyRight: 2020 liaoyongxiang All rights reserved.
 **/
@Configuration
@EnableAsync
@EnableScheduling
@Slf4j
public class TaskPoolConfig implements AsyncConfigurer {

    /**
     * 异步任务执行线程池
     *
     * @return
     */
    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        taskExecutor.setCorePoolSize(20);
        //配置最大线程数
        taskExecutor.setMaxPoolSize(50);
        //配置队列大小
        taskExecutor.setQueueCapacity(99999);
        //除核心线程外的线程存活时间
        //taskExecutor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        taskExecutor.setThreadNamePrefix("video-taskExecutor-");
        //CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有线程结束之后关闭线程池
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        //taskExecutor.setAwaitTerminationSeconds(60);
        //执行初始化
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return taskExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            log.error("异步任务执行出现异常, message {}, method {}, params {}", throwable, method, objects);
        };
    }

}
